package com.pentalog.webservice;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.ws.server.endpoint.AbstractJDomPayloadEndpoint;
import org.springframework.ws.server.endpoint.annotation.Endpoint;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;

import com.pentalog.bo.StringReveralService;

@Endpoint
@SuppressWarnings("deprecation")
public class StringReversalServiceEndPoint extends AbstractJDomPayloadEndpoint {
	public static final String NAMESPACE = "http://www.javabeat.net/spring/spring-ws/articles/reversal-service";
	
	@Autowired
	private StringReveralService stringReversalService;

	public void setStringReveralService(
			StringReveralService stringReveralService) {
		this.stringReversalService = stringReveralService;
	}

	protected Element invokeInternal(Element requestElement)
			throws Exception {
		String requestString = findRequestString(requestElement);
		String reversedString = invokeServiceAndReturnResponse(requestString);
		Element responseXml = prepareResponseXml(reversedString);
		return responseXml;
	}

	private static String findRequestString(Element requestElement) {
		NodeList childNodes = requestElement.getChildNodes();
		String requestString = null;
		for (int i = 0; i < childNodes.getLength(); i++) {
			if (childNodes.item(i).getNodeType() == Node.TEXT_NODE) {
				Text tempText = (Text) childNodes.item(i);
				requestString = tempText.getNodeValue();
				break;
			}
		}
		return requestString;
	}

	private String invokeServiceAndReturnResponse(String requestString) {
		String reversedString = stringReversalService.reverse(requestString);
		return reversedString;
	}

	private static Element prepareResponseXml(String responseString) {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		Document document = null;
	    try {
	      DocumentBuilder builder = factory.newDocumentBuilder();
	      document = builder.newDocument();
	    }catch (ParserConfigurationException parserException) {
	      parserException.printStackTrace();
	    }
		Element responseElement = document.createElementNS(NAMESPACE,
				"stringReveralResponse");
		Text responseText = document.createTextNode(responseString);
		responseElement.appendChild(responseText);
		return responseElement;
	}

	@Override
	protected org.jdom2.Element invokeInternal(org.jdom2.Element arg0)
			throws Exception {
		// TODO Auto-generated method stub
		return null;
	}
}
